<template>
  <div>
    <el-form :model="addForm" :inline="true" :rules="addRules" ref="addForm" class="demo-ruleForm">
      <el-form-item label="标题" prop="title">
        <el-input v-model="addForm.title"></el-input>
      </el-form-item>
      <br />
      <el-form-item label="新旧" prop="isNew">
        <el-radio-group v-model="addForm.isNew">
          <el-radio-button label="0">全新</el-radio-button>
          <el-radio-button label="1">非全新</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <br />
      <el-form-item label="价格" prop="price">
        <el-input @keydown="handleInput" v-model="addForm.price"></el-input>
      </el-form-item>
      <br />
      <el-form-item label="原价" prop="oprice">
        <el-input v-model="addForm.oprice"></el-input>
      </el-form-item>
      <br />
      <!-- 手机号格式校验 -->
      <el-form-item label="电话" prop="phone">
        <el-input v-model="addForm.phone"></el-input>
      </el-form-item>
      <br />
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addForm.name"></el-input>
      </el-form-item>
      <br />
      <el-form-item label="所在省" prop="provinceId">
        <el-select
          placeholder="请选择省份"
          @change="findCity(addForm.provinceId)"
          v-model="addForm.provinceId"
        >
          <el-option
            v-for="item in location.province"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在市" prop="cityId">
        <el-select placeholder="请选择城市" @change="findArea(addForm.cityId)" v-model="addForm.cityId">
          <el-option
            v-for="item in location.city"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在区" prop="areaId">
        <el-select placeholder="请选择区域" v-model="addForm.areaId">
          <el-option
            v-for="item in location.area"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <br />
      <el-form-item label="上传图片" prop="paths">
        <el-upload
          action="http://etoak.vip:9527/sysFile/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :limit="3"
          :on-success="handleAvatarSuccess"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :show-file-list="true"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>
      <br />
      <el-form-item label="宝贝描述" prop="description">
        <el-input type="textarea" v-model="addForm.description"></el-input>
      </el-form-item>
      <br />
      <el-form-item>
        <el-button type="primary" @click="addData('addForm')">立即发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import shopApi from "@/api/shop";
export default {
  data() {
    let checkphone = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error("请输入手机号"));
      } else if (!this.isCellPhone(value)) {
        callback(new Error("请输入合法手机号码!"));
      } else {
        callback();
      }
    };
    let checkPrice = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error("请输入价格"));
      } else if (!this.isPrice(value)) {
        console.log(this.isPrice(value));
        console.log("已经校验");
        callback(new Error("请输入合法价格!"));
      } else {
        callback();
      }
    };
    return {
      addForm: {
        title: "",
        name: "",
        isNew: '1',
        oprice: "",
        price: "",
        phone: "15973626178",
        description: "描述",
        provinceId: "",
        cityId: "",
        areaId: "",
        key: "5749495156575544565e501c180b585049505f",
        paths: []
      },
      addRules: {
        price: [
          {
            //required: true,
            //message: "请填写价格",
            validator: checkPrice,
            trigger: "blur"
          }
        ],
        oprice: [
          {
            /* required: true, message: "请填写原价", */ validator: checkPrice,
            trigger: "blur"
          }
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号正确格式",
            validator: checkphone,
            trigger: "blur"
          }
        ],
        name: [
          { required: true, message: "请填写姓名", trigger: "blur" },
          { min: 2, max: 4, message: "用户名在2到4位之间", trigger: "blur" }
        ],
        title: [{ required: true, message: "请填写标题", trigger: "blur" }],
        provinceId: [
          { required: true, message: "请选择省份", trigger: "change" }
        ],
        cityId: [{ required: true, message: "请选择城市", trigger: "change" }],
        areaId: [{ required: true, message: "请选择区域", trigger: "change" }],
        description: [
          { required: true, message: "请选择区域", trigger: "blur" }
        ]
      },
      location: {
        // 省市区级联
        province: this.searchProvince(),
        city: [],
        area: []
      },
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false
    };
  },
  methods: {
    addData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //console.log(this.addForm);
          shopApi.addShop(this.addForm).then(response => {
            console.log(response.data);
            const resp = response.data;
            if (resp.flag) {
              this.$message({
                message: resp.msg,
                type: "success"
              });
            } else {
              this.$message({
                message: resp.msg,
                type: "warning"
              });
            }
          });
        }
      });
    },
    handleInput(e) {
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,1})/g)[0] || null;
    },
    /* 此函数用来验证手机号码 */
    isCellPhone(val) {
      /* 传入正则表达式 */
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false;
      } else {
        return true;
      }
    },
    isPrice(val) {
      if (!/^[1-9]{1}\d*(.\d{1,2})?$|^0.\d{1,2}$/.test(val)) {
        console.log("正在校验价格");
        return false;
      } else {
        return true;
      }
    },
    searchProvince() {
      //this.location.province = [];
      //查找省份
      shopApi.searchLocation(0).then(response => {
        const resp = response.data;
        if (resp.flag) {
          this.location.province = resp.data;
        }
      });
    },
    findCity(pid) {
      this.addForm.cityId = null;
      this.addForm.areaId = null;
      //查找城市
      shopApi.searchLocation(pid).then(response => {
        const resp = response.data;
        if (resp.flag) {
          this.location.city = resp.data;
        }
      });
    },
    findArea(pid) {
      this.addForm.areaId = null;
      //查找区域
      shopApi.searchLocation(pid).then(response => {
        const resp = response.data;
        if (resp.flag) {
          this.location.area = resp.data;
        }
      });
    },
    /* 文件上传的方法 */
    /* 文件移除的钩子 */
    handleRemove(file, fileList) {
      //console.log(file.url, fileList);
      this.addForm.paths.splice(this.addForm.paths.indexOf(file.url), 1);
      /* 此处进行上传文件被删除之后的逻辑 */
    },
    /* 点击上传文件的钩子 */
    handlePictureCardPreview(file) {
      //this.addForm.paths = [];
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      //console.log('file.url',file.url);
    },
    //文件上传成功
    handleAvatarSuccess(response, paths, fileList) {
      this.addForm.paths.push(response.data.path);
    },
    /* 传递参数超过个数 */
    handleExceed(file, fileList) {
      this.$message.error("最多传递三张图片！");
    },
    /* 上传之前的钩子 */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
    /* 结束 */
  }
};
</script>

<style scoped>
</style>